﻿/* 变量 */
var newst = "NewSmartTravel.html";
var mysmart = "MySmartTravel.html";
var myplandetail = "MyPlanDetail.html";
var myeditplandetail = "ditMySmartTravel.html";
var mainsmarttravel = "MainSmartTravel.html";


var contactsCallback_main = myApp.onPageInit('mainsmart', function (page) {
    var index_tab1 = 1;
    var current_tabindex = 0;
    var size = 10;
    //获取页面参数
    var userID = ISS.utils.getParameter("userID");
    if (userID && userID != undefined && userID != null && userID != "") {
        iss_localStorage.set("yuqing_appUserId", userID);
    }
    if (userID = "") {
        userID = iss_localStorage.get("yuqing_appUserId")
    }
    var para = new Object();
    para.PageIndex = index_tab1
    para.PageSize = size
    para.UserID = iss_localStorage.get("yuqing_appUserId");
    //获取我的行程
    myApp.showPreloader()
    var conditionParams = {
        serviceName: ISS_Constants.PortalServiceName.AddSmarttragel,
        Type: 3,
        content: JSON.stringify({
            Calltype: "T_4",
            jsonParm: para,
        }),
    };
    $$.ajax({
        url: ISS_Constants.Url.const_portal_url,
        data: conditionParams,
        dataType: 'jsonp',
        jsonp: 'callback',
        success: function (data, status) {
            data = JSON.parse(data);
            if (data && data.ListTourPlan != null && data.ListTourPlan.length > 0) {
                var minehtml = "<div class='my-trip clearfix'><div class='title'>我的行程<a href='#' data-href='../../view/SmartTravel/MySmartTravel.html'>更多&gt;</a></div><div class='trip-content'><div class='row'>";
                for (var i = 0; i < data.ListTourPlan.length; i++) {
                    if (i > 3 || i == data.ListTourPlan.length) {
                        minehtml += "</div></div> <div class='addplan'><a href='#' data-href='../../view/SmartTravel/NewSmartTravel.html'>创建我的行程</a></div></div>"
                        break;;

                    } else if (i % 2 == 0 && i != 0) {
                        minehtml += "</div><div class='row'>"
                        minehtml += "<div class='col-50'>" +
                            "<a href='#' data-href='../../view/SmartTravel/MyPlanDetail.html?ID=" + data.ListTourPlan[i].ID + "&type=1'>" +
                            "    <div class='t-photo' style='background-image:url(" + data.ListTourPlan[i].ImgPath + ")'>" +
                            "         <span>" + data.ListTourPlan[i].PlanDays + "天</span>" +
                            "    </div>" +
                            "    <div class='t-text'>" +
                            "        <div class='t-tit'>" + data.ListTourPlan[i].TourName + "</div>" +
                            "        <dl class='date clearfix'>" +
                            "            <dt>出发时间：</dt>" +
                            "            <dd>" + data.ListTourPlan[i].BeginDate + "</dd>" +
                            "        </dl>" +
                            "    </div>" +
                            "</a></div>"
                    }
                    else {
                        minehtml += "<div class='col-50'>" +
                            "<a href='#' data-href='../../view/SmartTravel/MyPlanDetail.html?ID=" + data.ListTourPlan[i].ID + "&type=1'>" +
                            "    <div class='t-photo' style='background-image:url(" + data.ListTourPlan[i].ImgPath + ")'>" +
                            "         <span>" + data.ListTourPlan[i].PlanDays + "天</span>" +
                            "    </div>" +
                            "    <div class='t-text'>" +
                            "        <div class='t-tit'>" + data.ListTourPlan[i].TourName + "</div>" +
                            "        <dl class='date clearfix'>" +
                            "            <dt>出发时间：</dt>" +
                            "            <dd>" + data.ListTourPlan[i].BeginDate + "</dd>" +
                            "        </dl>" +
                            "    </div>" +
                            "</a></div>"
                    }
                }
                $$('.p-bg').remove();
                $$('.addplan').remove();
                $('.retrip').before(minehtml);
            }
        },
        error: function (xhr, status) { myApp.hidePreloader(); }
    });
    //获取推荐行程
    var conditionParams = {
        serviceName: ISS_Constants.PortalServiceName.AddSmarttragel,
        Type: 3,
        content: JSON.stringify({
            Calltype: "T_13",
            jsonParm: para,
        }),
    };
    $$.ajax({
        url: ISS_Constants.Url.const_portal_url,
        data: conditionParams,
        dataType: 'jsonp',
        jsonp: 'callback',
        success: function (data, status) {
            data = JSON.parse(data);
            if (data && data.ListTourPlan != null && data.ListTourPlan.length > 0) {
                var searchTemplate = $$('#template-clearfix-tuijian').html();
                if (searchTemplate) {
                    var p3html = "";
                    if (searchTemplate) {
                        var compiledTemplate = Template7.compile(searchTemplate);
                        p3html += compiledTemplate(data);
                        $$(".tuijianxc").html(p3html)
                    }
                    flag_InfiniteScroll = flag_needScroll = true; myApp.hidePreloader();
                }
            }
        },
        error: function (xhr, status) { myApp.hidePreloader(); }
    });


})
var contactsCallback_newst = myApp.onPageInit('newst', function (page) {
    var mySwiper = myApp.swiper('.swiper-container', {
        pagination: '.swiper-pagination'
    });
    $$('.swiper-pagination').css('display', 'none')

    // 过滤
    $$(".navbar-inner .right img").hide();
    //获取页面参数
    var userID = ISS.utils.getParameter("userID");
    if (userID && userID != undefined && userID != null && userID != "") {
        iss_localStorage.set("yuqing_appUserId", userID);
    }
    //删除滚动后重新添加滚动
    var flag_InfiniteScroll = true;
    //是否需要滚动加载
    var flag_needScroll = true;
    //滚动事件只执行一次
    var flag_execute = false;

    $$(".num-box a.plus").click(function () {
        if ($$(this).hasClass("unable")) return;
        var num = $$(".num-box span").html();
        num = parseInt(num) + 1;
        if (num >= 5) $$(this).addClass("unable");
        $$(".num-box span").html(num);
        if (num > 1) $$(".num-box a.minus").removeClass("unable");

    })
    //减
    $$(".num-box a.minus").click(function () {
        if ($$(this).hasClass("unable")) return;
        var num = $$(".num-box span").html();
        num = parseInt(num) - 1;
        if (num <= 1) $$(this).addClass("unable");
        if (num < 5) $$(".num-box a.plus").removeClass("unable");
        $$(".num-box span").html(num);

    })

    /*====================================
    ** 日历 相关
    **==================================*/
    loadDatepicker();
    function loadDatepicker() {
        var monthNames = ['1月', '2月', '03月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
        var calendarInline = myApp.calendar({
            input: 'a.drop_picker',
            value: [new Date()],
            minDate: GetDateStr(0),
            monthNames: monthNames,
            dateFormat: 'yyyy-mm-dd',
            dayNamesShort: ['日', '一', '二', '三', '四', '五', '六'],
            toolbarTemplate:
            '<div class="toolbar calendar-custom-toolbar">' +
            '<div class="toolbar-inner">' +
            '<div class="left">' +
            '<a href="#" class="link icon-only"><i class="icon icon-back"></i></a>' +
            '</div>' +
            '<div class="center"></div>' +
            '<div class="right">' +
            '<a href="#" class="link icon-only"><i class="icon icon-forward"></i></a>' +
            '</div>' +
            '</div>' +
            '</div>',
            onOpen: function (p) {
                $$('.calendar-custom-toolbar .center').text(p.currentYear + "年" + monthNames[p.currentMonth]);
                $$('.calendar-custom-toolbar .left .link').on('click', function () {
                    calendarInline.prevMonth();
                });
                $$('.calendar-custom-toolbar .right .link').on('click', function () {
                    calendarInline.nextMonth();
                });
            },
            onMonthYearChangeStart: function (p) {
                $$('.calendar-custom-toolbar .center').text(p.currentYear + "年" + monthNames[p.currentMonth]);
            },
            onDayClick: function (p, dayContainer, year, month, day) {
                $$("a.drop_picker.year").html(year + "年 " + checkTime(parseInt(month) + 1) + "月 " + checkTime(day) + "日" + '<i class="iconfont icon-jiantou"></i>');
                $$("a.drop_picker.year").attr("date", year + "-" + checkTime(parseInt(month) + 1) + "-" + checkTime(day));
            }
        });
        var myDate = new Date();
        var nowy = myDate.getFullYear(); //当前年
        var nowm = myDate.getMonth() + 1; //当前月
        var nowd = myDate.getDate(); //当前日
        var datettml = nowy + "年 ";
        datettml += checkTime(nowm) + "月 ";
        datettml += checkTime(nowd) + "日";
        datettml += '<i class="iconfont icon-jiantou"></i>';
        $$("a.drop_picker.year").html(datettml).attr("date", nowy + "-" + checkTime(nowm) + "-" + checkTime(nowd));
        $$('.icon-jiantou').css('display', 'none')
    }
    function checkTime(k) {
        if (k.toString().length == 1) {
            k = "0" + k;
        }
        return k;
    }
    function GetDateStr(AddDayCount) {
        var dd = new Date();
        dd.setDate(dd.getDate() + AddDayCount); //获取AddDayCount天后的日期 
        var y = dd.getFullYear();
        var m = dd.getMonth() + 1; //获取当前月份的日期 
        var d = dd.getDate();
        return y + "-" + m + "-" + d;
    }
    //加载数据
    loaddata();
    //添加行程
    addsmarttrave(iss_localStorage.get("yuqing_appUserId"));

})
var contactsCallback_mysmart = myApp.onPageInit('mysmart', function (page) {
    //跳转判断
    CheckPopLogin(function () {
        // 过滤
        $$(".navbar-inner .right img").hide();
        loadDatepicker();
        function loadDatepicker() {
            var monthNames = ['1月', '2月', '03月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
            var calendarInline = myApp.calendar({
                input: 'a.drop_picker',
                value: [new Date()],
                minDate: GetDateStr(0),
                monthNames: monthNames,
                dateFormat: 'yyyy-mm-dd',
                dayNamesShort: ['日', '一', '二', '三', '四', '五', '六'],
                toolbarTemplate:
                '<div class="toolbar calendar-custom-toolbar">' +
                '<div class="toolbar-inner">' +
                '<div class="left">' +
                '<a href="#" class="link icon-only"><i class="icon icon-back"></i></a>' +
                '</div>' +
                '<div class="center"></div>' +
                '<div class="right">' +
                '<a href="#" class="link icon-only"><i class="icon icon-forward"></i></a>' +
                '</div>' +
                '</div>' +
                '</div>',
                onOpen: function (p) {
                    $$('.calendar-custom-toolbar .center').text(p.currentYear + "年" + monthNames[p.currentMonth]);
                    $$('.calendar-custom-toolbar .left .link').on('click', function () {
                        calendarInline.prevMonth();
                    });
                    $$('.calendar-custom-toolbar .right .link').on('click', function () {
                        calendarInline.nextMonth();
                    });
                },
                onMonthYearChangeStart: function (p) {
                    $$('.calendar-custom-toolbar .center').text(p.currentYear + "年" + monthNames[p.currentMonth]);
                },
                onDayClick: function (p, dayContainer, year, month, day) {
                    $$("a.drop_picker.year").html(year + "年 " + checkTime(parseInt(month) + 1) + "月 " + checkTime(day) + "日" + '<i class="iconfont icon-jiantou"></i>');
                    $$("a.drop_picker.year").attr("date", year + "-" + checkTime(parseInt(month) + 1) + "-" + checkTime(day));
                }
            });
            var myDate = new Date();
            var nowy = myDate.getFullYear(); //当前年
            var nowm = myDate.getMonth() + 1; //当前月
            var nowd = myDate.getDate(); //当前日
            var datettml = nowy + "年 ";
            datettml += checkTime(nowm) + "月 ";
            datettml += checkTime(nowd) + "日";
            datettml += '<i class="iconfont icon-jiantou"></i>';
            $$("a.drop_picker.year").html(datettml).attr("date", nowy + "-" + checkTime(nowm) + "-" + checkTime(nowd));
            $$('.icon-jiantou').css('display', 'none')
        }
        function checkTime(k) {
            if (k.toString().length == 1) {
                k = "0" + k;
            }
            return k;
        }
        function GetDateStr(AddDayCount) {
            var dd = new Date();
            dd.setDate(dd.getDate() + AddDayCount); //获取AddDayCount天后的日期 
            var y = dd.getFullYear();
            var m = dd.getMonth() + 1; //获取当前月份的日期 
            var d = dd.getDate();
            return y + "-" + m + "-" + d;
        }
        //删除滚动后重新添加滚动
        var flag_InfiniteScroll = true;
        //是否需要滚动加载
        var flag_needScroll = true;
        //滚动事件只执行一次
        var flag_execute = false;

        var index_tab1 = 1;
        var current_tabindex = 0;
        var size = 10;
        //获取页面参数
        var userID = ISS.utils.getParameter("userID");
        if (userID && userID != undefined && userID != null && userID != "") {
            iss_localStorage.set("yuqing_appUserId", userID);
        }
        LoadNewsAll(index_tab1, size);
        function LoadNewsAll(pageindex, pagesize) {
            myApp.showPreloader()
            var para = new Object();
            para.PageIndex = index_tab1
            para.PageSize = size
            para.UserID = iss_localStorage.get("yuqing_appUserId");

            var conditionParams = {
                serviceName: ISS_Constants.PortalServiceName.AddSmarttragel,
                Type: 3,
                content: JSON.stringify({
                    Calltype: "T_4",
                    jsonParm: para,
                }),
            };

            $$.ajax({
                url: ISS_Constants.Url.const_portal_url,
                data: conditionParams,
                dataType: 'jsonp',
                jsonp: 'callback',
                success: function (data, status) {
                    myApp.hidePreloader();
                    data = JSON.parse(data);
                    if (data && data.ListTourPlan != null && data.ListTourPlan.length > 0) {

                        var searchTemplate = $$('#template-mysmart-info').html();
                        if (searchTemplate) {
                            var p3html = "";
                            if (searchTemplate) {
                                var compiledTemplate = Template7.compile(searchTemplate);
                                p3html += compiledTemplate(data);
                                $$('.plan-list').html(p3html)
                            }
                            $$('.right').click(function () {
                                if ($$('.plan-edit').length > 0) {
                                    $$('.plan-edit').remove();
                                } else {
                                    $$(".plan-list .planmain").each(function () {
                                        guanli($$(this));
                                    })
                                }
                            })
                            flag_InfiniteScroll = flag_needScroll = true;
                        }
                    }
                },
                error: function (xhr, status) { myApp.hidePreloader(); }
            });
        }
    });
})
var contactsCallback_myplandetail = myApp.onPageInit('myplandetail', function (page) {
    var map = new BMap.Map("mapcontent");
    // 过滤
    $$("#myplandetail .navbar-inner .right img").hide();

    //删除滚动后重新添加滚动
    var flag_InfiniteScroll = true;
    //是否需要滚动加载
    var flag_needScroll = true;
    //滚动事件只执行一次
    var flag_execute = false;

    var index_tab1 = 1;
    var current_tabindex = 0;
    var size = 10;
    var type = ISS.utils.getParameter("type");

    //获取页面参数
    var userID = ISS.utils.getParameter("userID");
    if (userID && userID != undefined && userID != null && userID != "") {
        iss_localStorage.set("yuqing_appUserId", userID);
    }
    if (userID == "") {
        userID = iss_localStorage.get("yuqing_appUserId");
    }
    myApp.showPreloader("")
    if (type == 2) {
        $$('#myplandetail .center').css({ "left": "14px" })
        $$('#myplandetail .right').html("<div class='addMyPlant'><p>加入行程</p></div>")
        $$('#myplandetail .center').html("行程详情")
        $$('#myplandetail .addMyPlant').on('click', function () {
            myApp.showPreloader('发布中.....')
            var conditionParams = {
                serviceName: ISS_Constants.PortalServiceName.CopyTravelPlan,
                planMainID: ISS.utils.getParameter("ID"),
                userId: userID,
                type: 4,
                content: JSON.stringify({
                    planMainID: ISS.utils.getParameter("ID"),
                    userId: userID,
                }),
            };
            $$.ajax({
                url: ISS_Constants.Url.const_portal_url,
                data: conditionParams,
                dataType: 'jsonp',
                jsonp: 'callback',
                success: function (data, status) {
                    data = JSON.parse(data);
                    if (data && data != "") {
                        myApp.hidePreloader();
                        myApp.alert('发布成功', function () {
                            window.location.href = "MainSmartTravel.html";
                        });
                    }
                    else {
                        myApp.hidePreloader();
                        myApp.alert('发布失败');
                    }
                },
                error: function (xhr, status) {
                    myApp.hidePreloader();
                    myApp.alert('发布失败');
                }
            });
        })
    }


    LoadNewsAll(index_tab1, size);
    function LoadNewsAll(pageindex, pagesize) {
        var para = new Object();
        //获取页面参数
        para.ID = ISS.utils.getParameter("ID");
        if (page != undefined) {
            para.ID = page.query.ID;
        }
        if (para.ID == "") {
            para.ID = iss_localStorage.get("yuqing_appUserId")
        }
        var conditionParams = {
            serviceName: ISS_Constants.PortalServiceName.AddSmarttragel,
            Type: 3,
            content: JSON.stringify({
                Calltype: "T_2",
                jsonParm: para.ID,
            }),
        };

        $$.ajax({
            url: ISS_Constants.Url.const_portal_url,
            data: conditionParams,
            dataType: 'jsonp',
            jsonp: 'callback',
            success: function (data, status) {
                data = JSON.parse(data);
                if (data && data.length > 0) {
                    var searchTemplate = $$('#template-myplandetail-info').html();
                    if (searchTemplate) {
                        var p3html = "";
                        if (searchTemplate) {
                            $$('#myplandetail .plan-top img').attr('src', iss_localStorage.get("yuqing_appUserSRC"));
                            $$('#myplandetail .center').html(iss_localStorage.get("yuqing_appUserNickName"));
                            gettimesdiscript(map, data, data[1].length, 0, 0, 0);
                        }
                        flag_InfiniteScroll = flag_needScroll = true;
                    }
                }
            },
            error: function (xhr, status) { myApp.hidePreloader(); }
        });

    }

})

var para = new Object();
var ifRefresh = false;
var contactsCallback_myeditplandetail = myApp.onPageInit('myeditplandetail', function (page) {
    var source = iss_localStorage.get("yuqing_source");
    iss_localStorage.set("yuqing_source", "");

    var loaderData = function () {
        // 过滤
        source = new Object();

        //删除滚动后重新添加滚动
        var flag_InfiniteScroll = true;
        //是否需要滚动加载
        var flag_needScroll = true;
        //滚动事件只执行一次
        var flag_execute = false;

        LoadNewsAll();
        function LoadNewsAll() {

            //获取页面参数
            para.ID = ISS.utils.getParameter("ID");
            if (page != undefined) {
                para.ID = page.query.ID;
            }
            if (para.ID == "") {
                para.ID = iss_localStorage.get("yuqing_appUserId")
            }

            myApp.showPreloader()
            var conditionParams = {
                serviceName: ISS_Constants.PortalServiceName.AddSmarttragel,
                Type: 3,
                content: JSON.stringify({
                    Calltype: "T_2",
                    jsonParm: para.ID,
                }),
            };

            $$.ajax({
                url: ISS_Constants.Url.const_portal_url,
                data: conditionParams,
                dataType: 'jsonp',
                jsonp: 'callback',
                success: function (data, status) {
                    data = JSON.parse(data);
                    if (data && data.length > 0) {
                        source = data[1];
                        initData(source);
                    }
                },
                error: function (xhr, status) { myApp.hidePreloader(); }
            });
        }
    }

    var getTotal = function (plandayid) {
        var total = 0;
        $$("#plan-editdetail li").each(function () {
            if ($$(this).attr("planDayID") == plandayid) {
                total++;
            }
        })
        return total;
    }

    var addBeforeDay = function (dayName) {
        var index = 0;
        var plandate = "";
        var plandayid = ISS.utils.randomInt(1000000, 9999999);

        for (var i = 0; i < source.length; i++) {
            if (dayName == source[i].dayName) {
                index = i;
                plandate = source[i].planDate;
                break;
            }
        }

        var obj = {
            planProjectID: "",
            projectType: "",
            projectName: "",
            projectShortName: "",
            projectId: "",
            PX: 1,
            img: "",
            remark: "",
            time: "",
            price: "0.00",
            time4open: "",
            address: "",
            subAddress: "",
            phone: "",
            longitude: "",
            latitude: "",
            district: "",
            isCollect: "",
            planCollectID: "",
            planDayID: plandayid,
            planDate: plandate,
            dayName: dayName,
            attractionsStar: "",
            hotelStar: "",
            entertainmentType: ""
        }

        source.splice(index, 0, obj);
        for (var i = index + 1; i < source.length; i++) {
            source[i].dayName = (parseInt(source[i].dayName) + 1).toString();
            source[i].planDate = ISS.utils.dateToStr("yyyy/MM/dd HH:mm:ss", new Date(ISS.utils.strToDate(source[i].planDate).getTime() + 24 * 60 * 60 * 1000));
        }
        iss_localStorage.set("yuqing_source", JSON.stringify(source));
        mainView.router.refreshPage();
    }

    var addAfterDay = function (dayName) {
        var index = 0;
        var plandate = "";
        var plandayid = ISS.utils.randomInt(1000000, 9999999);
        for (var i = 0; i < source.length; i++) {
            if (parseInt(source[i].dayName) > dayName) {
                index = i;
                plandate = source[i].planDate;
                break;
            }
            if (i == source.length - 1) {
                index = source.length;
                plandate = ISS.utils.dateToStr("yyyy/MM/dd HH:mm:ss", new Date(ISS.utils.strToDate(source[i].planDate).getTime() + 24 * 60 * 60 * 1000));
            }
        }

        var obj = {
            planProjectID: "",
            projectType: "",
            projectName: "",
            projectShortName: "",
            projectId: "",
            PX: 1,
            img: "",
            remark: "",
            time: "",
            price: "0.00",
            time4open: "",
            address: "",
            subAddress: "",
            phone: "",
            longitude: "",
            latitude: "",
            district: "",
            isCollect: "",
            planCollectID: "",
            planDayID: plandayid,
            planDate: plandate,
            dayName: (parseInt(dayName) + 1).toString(),
            attractionsStar: "",
            hotelStar: "",
            entertainmentType: ""
        }

        source.splice(index, 0, obj);
        for (var i = index + 1; i < source.length; i++) {
            source[i].dayName = (parseInt(source[i].dayName) + 1).toString();
            source[i].planDate = ISS.utils.dateToStr("yyyy/MM/dd HH:mm:ss", new Date(ISS.utils.strToDate(source[i].planDate).getTime() + 24 * 60 * 60 * 1000));
        }
        iss_localStorage.set("yuqing_source", JSON.stringify(source));
        mainView.router.refreshPage();
    }

    var delThatDay = function (dayName) {
        var index = 0;
        var curdayTotal = 0;
        for (var i = 0; i < source.length; i++) {
            if (source[i].dayName == dayName) {
                index = i;
                break;
            }
        }

        for (var i = 0; i < source.length; i++) {
            if (source[i].dayName == dayName) {
                curdayTotal++;
            }
        }

        source.splice(index, curdayTotal);
        for (var i = index; i < source.length; i++) {
            source[i].dayName = (parseInt(source[i].dayName) - 1).toString();
            source[i].planDate = ISS.utils.dateToStr("yyyy/MM/dd HH:mm:ss", new Date(ISS.utils.strToDate(source[i].planDate).getTime() - 24 * 60 * 60 * 1000));
        }
        iss_localStorage.set("yuqing_source", JSON.stringify(source));
        mainView.router.refreshPage();
    }

    var cleanEmptyDay = function () {
        ifRefresh = false;
        var plandate = ISS.utils.dateToStr("yyyy/MM/dd HH:mm:ss", new Date(ISS.utils.strToDate(source[0].planDate).getTime() - 24 * 60 * 60 * 1000));;
        var dayName = 0;
        for (var i = 0; i < source.length; i++) {
            if (source[i].projectShortName == "") {
                ifRefresh = true;
                source.splice(i, 1);
                i--;
            }
        }
        if (source.length == 0) {
            myApp.alert("行程内容不能为空！")
        }

        if (ifRefresh) {
            for (var i = 0; i < source.length; i++) {
                if (source[i].PX == 1) {
                    dayName++;
                    plandate = ISS.utils.dateToStr("yyyy/MM/dd HH:mm:ss", new Date(ISS.utils.strToDate(plandate).getTime() + 24 * 60 * 60 * 1000));;
                    source[i].dayName = dayName;
                    source[i].planDate = plandate;
                } else {
                    source[i].dayName = dayName;
                    source[i].planDate = plandate;
                }
            }
            iss_localStorage.set("yuqing_source", JSON.stringify(source));
            mainView.router.refreshPage();
        } else {
            editsmart(source, para.ID);
        }
    }

    var initData = function (source) {
        var searchTemplate = $$('#template-myeditplandetail-info').html();
        if (searchTemplate) {
            var p3html = "";
            if (searchTemplate) {
                var p3html = "";
                var searchTemplate = $$('#template-myeditplandetail-info').html();
                var compiledTemplate = Template7.compile(searchTemplate);
                p3html += compiledTemplate(source);
                $$("#plan-editdetail").html(p3html)
                if (ifRefresh) {
                    editsmart(source, para.ID);
                }
                $$('#myeditplandetail .right').on('click', 'a', function () {
                    cleanEmptyDay();
                })
                $$('#plan-editdetail li').on('click', 'a', function () {
                    if ($$('#plan-editdetail li').length <= 2) {
                        myApp.alert('不能删除，只剩一天行程了')
                    } else {
                        $$(this).parent().parent().parent().remove();
                    }
                })

                //start popover弹窗
                var popoverHTML = '<div class="popover popover-menu">' +
                    '<div class="popover-angle"></div>' +
                    '<div class="popover-inner">' +
                    '<div class="list-block">' +
                    '<ul>' +
                    '<li><a href="#" class="list-button add-before" style="display:flex;padding:10px 20px;border-bottom:1px solid white">' +
                    '<img src="../../assets/images/common/travelplan/plan_edit_add_before.png" style="height:20px;float:left"/><span style="color:white;flex:1;text-align: right;">增加前一天</span>' +
                    '</a></li>' +
                    '<li><a href="#" class="list-button add-after" style="display:flex;padding:10px 20px;border-bottom:1px solid white">' +
                    '<img src="../../assets/images/common/travelplan/plan_edit_add_after.png" style="height:20px;float:left"/><span style="color:white;flex:1;text-align: right;">增加后一天</span>' +
                    '</a></li>' +
                    '<li><a href="#" class="list-button del-that-day" style="display:flex;padding:10px 20px;border-bottom:1px solid white">' +
                    '<img src="../../assets/images/common/travelplan/plan_edit_del.png" style="height:20px;float:left"/><span style="color:white;flex:1;text-align: right;">删除该天</span>' +
                    '</a></li>' +
                    '<li><a href="#" class="list-button add-new-interests" style="display:flex;padding:10px 20px;">' +
                    '<img src="../../assets/images/common/travelplan/plan_edit_add_pro.png" style="height:20px;float:left"/><span style="color:white;flex:1;text-align: right;">添加兴趣点</span>' +
                    '</a></li>' +
                    '</ul>' +
                    '</div>' +
                    '</div>' +
                    '</div>';
                //end 

                $$("#plan-editdetail li .icon-shanchu").each(function () {
                    $$(this).on("click", function () {
                        var total = 0;
                        var plandayid = $$(this).parents('li').attr("planDayID");
                        var dayname = $$(this).parents('li').attr("dayName");
                        var projectid = $$(this).parents('li').attr("projectId");
                        total = getTotal(plandayid);
                        for (var i = 0; i < source.length; i++) {
                            if (source[i].dayName == dayname && source[i].projectId == projectid) {
                                if (total == 1) {
                                    source[i] = {
                                        planProjectID: "",
                                        projectType: "",
                                        projectName: "",
                                        projectShortName: "",
                                        projectId: "",
                                        PX: 1,
                                        img: "",
                                        remark: "",
                                        time: "",
                                        price: $$(this).parents('li').attr("price"),
                                        time4open: "",
                                        address: "",
                                        subAddress: "",
                                        phone: "",
                                        longitude: "",
                                        latitude: "",
                                        district: "",
                                        isCollect: "",
                                        planCollectID: "",
                                        planDayID: plandayid,
                                        planDate: $$(this).parents('li').attr("planDate"),
                                        dayName: dayname,
                                        attractionsStar: "",
                                        hotelStar: "",
                                        entertainmentType: ""
                                    }
                                } else {
                                    source.splice(i, 1);
                                }
                            }
                        }
                    })
                })

                //遍历点击菜单按钮实现四种功能
                $$("#plan-editdetail .editday").each(function (index) {
                    $$(this).on("click", function () {
                        var dayName = index + 1 + "";//编辑的天数

                        myApp.popover(popoverHTML, this);
                        //增加前一天
                        $$(".popover-menu .add-before").on("click", function () {
                            addBeforeDay(dayName);
                            myApp.closeModal('.popover-menu');
                        });

                        //增加后一天
                        $$(".popover-menu .add-after").on("click", function () {
                            addAfterDay(dayName);
                            myApp.closeModal('.popover-menu');
                        });

                        //删除该天
                        $$(".popover-menu .del-that-day").on("click", function () {
                            delThatDay(dayName);
                            myApp.closeModal('.popover-menu');
                        });

                        //添加兴趣点
                        $$(".popover-menu .add-new-interests").on("click", function () {

                            myApp.closeModal('.popover-menu');
                            //start popup弹窗
                            var popupHTML = '<div class="popup popup-menu menu" style="background: transparent;width: 100vw;padding:0 32vw;padding-top: calc((100vh - 36vw)/2);">' +
                                '<div class="item-type add-scenic" style="margin-left: 12vw;padding: 3vw;border-radius: 12vw;background-color:rgba(0,0,0,0.4);width:6vw;height: 6vw; ">' +
                                '<img src="../../assets/images/common/travelplan/plan_add_scenic.png" style="width:6vw;height: 6vw;"/>' +
                                '</div>' +
                                '<div style="display:flex;position: relative;">' +
                                '<div class="item-type add-business" style="padding: 3vw;border-radius: 12vw;background-color:rgba(0,0,0,0.4);width:6vw;height: 6vw; ">' +
                                '<img src="../../assets/images/common/travelplan/plan_add_business.png" style="width:6vw;height: 6vw;" />' +
                                '</div>' +
                                '<div class="item-type add-hotel" style="position:absolute;right:0;padding: 3vw;border-radius: 12vw;background-color:rgba(0,0,0,0.4);width:6vw;height: 6vw; ">' +
                                '<img src="../../assets/images/common/travelplan/plan_add_hotel.png" style="width:6vw;height: 6vw;"/>' +
                                '</div>' +
                                '</div>' +
                                '<div class="item-type add-amusement" style="margin-left:12vw;padding: 3vw;border-radius: 12vw;background-color:rgba(0,0,0,0.4);width:6vw;height: 6vw; ">' +
                                '<img src="../../assets/images/common/travelplan/plan_add_amusement.png" style="width:6vw;height: 6vw;"/>' +
                                '</div>' +
                                '</div>';
                            //end

                            myApp.popup(popupHTML);

                            $$(".popup-menu").on("click", function () {
                                myApp.closeModal(".popup-menu");
                            })

                            $$(".add-scenic").on("click", function () {
                                mainView.router.loadPage({ url: "../../view/SmartTravel/AddScenicInterest.html?dayName=" + dayName + "&source=" + JSON.stringify(source), reload: false });
                                myApp.closeModal('.popup-menu');
                            });

                            $$(".add-business").on("click", function () {
                                mainView.router.load({ url: "../../view/SmartTravel/AddBusinessInterest.html?dayName=" + dayName + "&source=" + JSON.stringify(source), reload: false });
                                myApp.closeModal('.popup-menu');
                            });

                            $$(".add-hotel").on("click", function () {
                                mainView.router.load({ url: "../../view/SmartTravel/AddHotelInterest.html?dayName=" + dayName + "&source=" + JSON.stringify(source), reload: false });
                                myApp.closeModal('.popup-menu');
                            });

                            $$(".add-amusement").on("click", function () {
                                mainView.router.load({ url: "../../view/SmartTravel/AddAmusementInterest.html?dayName=" + dayName + "&source=" + JSON.stringify(source), reload: false });
                                myApp.closeModal('.popup-menu');
                            });
                        });
                    })
                })
            }
            flag_InfiniteScroll = flag_needScroll = true; myApp.hidePreloader();
        }
    }

    if (source == undefined || source == "") {
        loaderData();
    } else {
        source = JSON.parse(source);
        initData(source);
    }
})

function initData() {
    var href = window.location.href;
    if (href.indexOf(newst) > -1) {
        contactsCallback_newst.trigger();
    } else if (href.indexOf(mysmart) > -1) {
        contactsCallback_mysmart.trigger();
    } else if (href.indexOf(myplandetail) > -1) {
        contactsCallback_myplandetail.trigger();
    } else if (href.indexOf(myeditplandetail) > -1) {
        contactsCallback_myeditplandetail.trigger();
    } else if (href.indexOf(mainsmarttravel) > -1) {
        contactsCallback_main.trigger();
    }
}

initData();

/********创建行程**********/
function initSmartSelects(pageContainer) {
    var page = $$(pageContainer);
    if (page.length === 0) return;
    var selects;
    if (page.is('.smart-select')) {
        selects = page;
    }
    else {
        selects = page.find('.smart-select');
    }
    if (selects.length === 0) return;

    selects.each(function () {
        var smartSelect = $$(this);

        var $$select = smartSelect.find('select');
        if ($$select.length === 0) return;

        var select = $$select[0];
        if (select.length === 0) return;

        var valueText = [];
        for (var i = 0; i < select.length; i++) {
            if (select[i].selected) valueText.push(select[i].textContent.trim());
        }

        var itemAfter = smartSelect.find('.item-after');

        if (itemAfter.length === 0) {
            smartSelect.find('.item-inner').append('<div class="item-after">' + valueText.join(', ') + '</div>');
        }
        else {
            var selectedText = itemAfter.text();

            if (itemAfter.hasClass('smart-select-value')) {
                for (i = 0; i < select.length; i++) {
                    select[i].selected = select[i].textContent.trim() === selectedText.trim();
                }
            } else {
                itemAfter.text(valueText.join(', '));
            }
        }


    });

};
function loaddata() {
    var conditionParams = JSON.stringify({
        type: 5,
    });
    $$.ajax({
        url: ISS_Constants.Url.defaulturl + ISS_Constants.serviceName.TOURPLAN,
        crossDomain: true,
        data: { content: conditionParams },
        dataType: "jsonp",
        method: "POST",
        success: function (data, status) {
            data = JSON.parse(data);
            if (data && data.results.length > 0) {
                var p2html = "";

                var searchTemplate = $$('#template-clearfix-info').html();
                if (searchTemplate) {
                    var compiledTemplate = Template7.compile(searchTemplate);
                    p2html += compiledTemplate(data);
                    $$("#xczt .clearfix").html(p2html);
                    $$("#xczt .clearfix").on('click', 'li', function () {
                        if ($$(this).attr('class') == "active") {
                            $$(this).removeClass('active')
                        } else {
                            $$(this).addClass('active');
                        }
                    })

                }
                var p3html = "";
                searchTemplate = $$('#template-brcg-info').html();

                if (searchTemplate) {
                    var compiledTemplate = Template7.compile(searchTemplate);
                    p3html += compiledTemplate(data);
                    $$("#brcg").html(p3html);
                    $$("#brcg").on('click', 'li', function () {
                        if ($$(this).find('input').is(':checked')) {
                            $$(this).find('.btn-newjd').css({ "background-image": "url('../../assets/images/common/travelplan/newjd.png')" })
                        } else {
                            $$(this).find('.btn-newjd').css({ "background-image": "url('../../assets/images/common/travelplan/newsjd.png')" })
                        }
                    })

                }
            }
            else {
                MyApp.alert('暂无数据');
            }
        },
        error: function (xhr, status) {
            MyApp.alert('获取失败');
        }
    });
}
function addsmarttrave(userid) {
    $$('.btn-step').click(function () {
        myApp.showPreloader('发布中.....')
        if ($$('.plan-name').val() == "") {
            $$('.plan-name').val("我的行程计划")
        }
        var para = new Object();
        var StrJson = new Object();
        //行程名称，计划天数，计划日期
        var AP = new Object();
        AP.dates = $$('.num-box').find('span').text();
        AP.yxj = "0"
        AP.cometime = $$('.year').attr('date')
        AP.sjap = "1"
        //当前地理位置
        var Origin = new Object();
        Origin.Latitude = "39.677368",
            Origin.Longitude = "115.460379",
            Origin.Address = "野三坡火车站"

        //来XX的目的
        var MD = new Object();
        MD.YL = "YL_SMART",
            MD.JQ = "000001,000002,000003,000004",
            MD.CT = "CT_SMART",
            MD.SQ = "SQ_SMART"
        //非去不可
        var TJ = new Object();
        TJ = CheckOption();


        StrJson.AP = AP;
        StrJson.Origin = Origin;
        StrJson.MD = MD;
        StrJson.TJ = TJ;
        para.StrJson = StrJson
        para.userId = userid;
        para.planName = $$('.plan-name').val()


        var conditionParams = {
            serviceName: ISS_Constants.PortalServiceName.AddSmarttragel,
            action: 2,
            Type: 3,
            content: JSON.stringify({
                Calltype: "T_3",
                jsonParm: para,
            }),
        };
        $$.ajax({
            url: ISS_Constants.Url.const_portal_url,
            data: conditionParams,
            dataType: 'jsonp',
            jsonp: 'callback',
            timeout: 10000,
            success: function (data, status) {
                if (data && data.status) {
                    myApp.hidePreloader();
                    myApp.alert('发布成功', function () {
                        window.location.href = "MainSmartTravel.html";
                    });
                }
                else {
                    myApp.hidePreloader();
                    myApp.alert('发布失败');
                }
            },
            error: function (xhr, status) {
                myApp.hidePreloader();
                myApp.alert('发布失败');
            },
            complete: function (XMLHttpRequest, status) { //请求完成后最终执行参数
                if (status == 'timeout') {//超时,status还有success,error等值的情况
                    myApp.hidePreloader();
                    // ajaxTimeoutTest.abort();
                    myApp.alert("请求超时");
                }
            },
        });
    })
}
function CheckOption() {
    var TJ = new Object();
    var JQ = Array();
    $$('#brcg li').each(function (i, v) {
        if ($$(this).find('input').is(':checked')) {
            var obj = new Object();
            obj.Code = $$(this).find('input').val();
            obj.Name = $$(this).find('.item-title').text();
            JQ.push(obj);
        }
    })
    TJ.JQ = JQ
    return TJ;
}
function fz(item, li) {
    if (li.find('.item-after').length > 0) {
        var strings = li.find('.item-after').text().split(', ')
        for (var n = 0; n < strings.length; n++) {
            li.find('option').each(function (k, z) {
                if (strings[n] == $$(this).text()) {
                    var obj = new Object();
                    obj.Code = $$(this).val()
                    obj.Name = $$(this).text()
                    item.push(obj);
                }
            })
        }
    }
    return item;
}
/*************************/

/*********我的行程*********/
function guanli(li) {
    var template = "<ul class='plan-edit clearfix'>" +
        "<li><a href='#'><i class='iconfont icon-date'></i>出发日期</a></li>" +
        "<li><a href='#'><i class='iconfont icon-iconbianji'></i>行程名称</a></li>" +
        "<li><a href='#'><i class='iconfont icon-delete'></i>删除</a></li>" +
        "</ul>";
    li.append(template);
    //删除计划
    delsmartrave(li);
    //修改计划名称
    modifysmartravetitle(li);
    //修改计划时间
    modifysmartravetime(li);
}
//删除计划
function delsmartrave(li) {
    li.find(".plan-edit li").eq(2).click(function () {
        myApp.showPreloader('删除中.....')
        id = li.attr('id');
        var conditionParams = {
            serviceName: ISS_Constants.PortalServiceName.AddSmarttragel,
            Type: 3,
            action: 2,
            content: JSON.stringify({
                Calltype: "T_7",
                jsonParm: id
            }),
        };
        $$.ajax({
            url: ISS_Constants.Url.const_portal_url,
            data: conditionParams,
            dataType: 'jsonp',
            jsonp: 'callback',
            type: "post",
            success: function (data, status) {
                if (data == "True") {
                    myApp.hidePreloader();
                    myApp.alert('删除成功', function () {
                        location.reload();
                    })
                } else {
                    myApp.hidePreloader();
                    myApp.alert('删除失败')
                }
            },
            error: function (xhr, status) {
                myApp.hidePreloader();
                myApp.alert('删除失败')
            }
        });
    })
}
//修改计划名称
function modifysmartravetitle(li) {
    li.find(".plan-edit li").eq(1).click(function () {
        myApp.popup('.popup-title');
        id = li.attr('id');
        var sourcetitle = li.find('.plan-name').text();
        $$('#title').val(sourcetitle);
        $$('.popup-title').on('close', function () {
            var title = $$('#title').val();
            if (title != sourcetitle) {
                var conditionParams = {
                    serviceName: ISS_Constants.PortalServiceName.AddSmarttragel,
                    Type: 3,
                    action: 2,
                    content: JSON.stringify({
                        Calltype: "T_6",
                        jsonParm: JSON.stringify({ ID: id, Title: title })
                    }),
                };
                $$.ajax({
                    url: ISS_Constants.Url.const_portal_url,
                    data: conditionParams,
                    dataType: 'jsonp',
                    jsonp: 'callback',
                    type: "post",
                    success: function (data, status) {
                        if (data == "True") {
                            myApp.alert('修改成功', function () {
                                location.reload();
                            })
                        } else {
                            myApp.alert('修改成功', function () {
                                location.reload();
                            })
                        }
                    },
                    error: function (xhr, status) {
                        myApp.alert('修改成功', function () {
                            location.reload();
                        })
                    }
                });
            }
        });
    })
}
//修改计划时间
function modifysmartravetime(li) {
    li.find(".plan-edit li").eq(0).click(function () {
        id = li.attr('id');
        $$('.year').attr('date', li.find('.plan-date span').text());
        var stime = li.find('.plan-date span').text().split("-")[0] + "年" + li.find('.plan-date span').text().split("-")[1] + "月" + li.find('.plan-date span').text().split("-")[2] + "日";
        $$('.year').text(stime)
        myApp.popup('.popup-time');
        $$('.popup-time').on('close', function () {
            var time = $$('.year').attr('date');

            if (li.find('.plan-date span').text() != time) {
                var conditionParams = {
                    serviceName: ISS_Constants.PortalServiceName.AddSmarttragel,
                    Type: 3,
                    action: 2,
                    content: JSON.stringify({
                        Calltype: "T_8",
                        jsonParm: JSON.stringify({ ID: id, Date: time })
                    }),
                };
                $$.ajax({
                    url: ISS_Constants.Url.const_portal_url,
                    data: conditionParams,
                    dataType: 'jsonp',
                    jsonp: 'callback',
                    type: "post",
                    success: function (data, status) {
                        if (data == "True") {
                            myApp.alert('修改成功', function () {
                                location.reload();
                            })
                        } else {
                            myApp.alert('修改失败')
                        }
                    },
                    error: function (xhr, status) {
                        myApp.alert('修改失败')
                    }
                });
            }
        })


    })
}
/*************************/

/********行程详情**********/
function gettimesdiscript(map, data, len, i, latitude, longitude) {
    if (data[1][i].PX == 1) {
        latitude = data[1][i].latitude
        longitude = data[1][i].longitude
        data[1][i].discripttitle = "第" + data[1][i].dayName + "天" + data[1][i].planDate.substring(0, data[1][i].planDate.indexOf(' '));
        i++;
        if (i < len) {
            gettimesdiscript(map, data, len, i, latitude, longitude)
        } else {
            settemplate(data);
        }
    } else if (data[1][i].PX > 1) {
        if (longitude == "" || latitude == "" || data[1][i].longitude == "" || data[1][i].latitude == "") {
            data[1][i].discripttitle = "";
            i++;
            if (i < len) {
                gettimesdiscript(map, data, len, i, latitude, longitude)
            } else {
                settemplate(data);
            }
            return;
        }
        var point1 = new BMap.Point(longitude, latitude);
        var point2 = new BMap.Point(data[1][i].longitude, data[1][i].latitude);
        var output = "";
        var searchComplete = function (results) {
            if (transit.getStatus() != BMAP_STATUS_SUCCESS) {
                return;
            }
            var plan = results.getPlan(0);
            output += plan.getDuration(true) + ";";                //获取时间
            output += "总路程为：";
            output += plan.getDistance(true) + ";";             //获取距离
            data[1][i].discripttitle = output;

        }
        var transit = new BMap.DrivingRoute(map, {
            renderOptions: { map: map },
            onSearchComplete: searchComplete,
            onPolylinesSet: function () {
                i++;
                if (i < len) {
                    gettimesdiscript(map, data, len, i, latitude, longitude)
                } else {
                    myApp.hidePreloader();
                    settemplate(data);
                }
            }
        });
        transit.search(point1, point2);
    }
}
function settemplate(data) {
    var p3html = "";
    var searchTemplate = $$('#template-myplandetail-info').html();
    $$('#days').html(data[1][data[1].length - 1].dayName)
    $$('#btime').html(data[0][0].BeginDate.substring(0, data[0][0].BeginDate.indexOf(' ')))
    iss_localStorage.set("yuqing_source", "");
    $$('#xqbj').attr('data-href', "EditMySmartTravel.html?ID=" + data[0][0].PlanMainID);
    $$('#xqbj').attr("data-action", "fw7");
    for (var i = 0; i < data[1].length; i++) {
        if (data[1][i].time4open == undefined || data[1][i].time4open == "" || data[1][i].time4open == "null") {
            data[1][i].time4open = "暂无时间";
        }
    }
    var compiledTemplate = Template7.compile(searchTemplate);
    p3html += compiledTemplate(data[1]);
    $$(".plan-detail").append(p3html)
}
/*************************/

/********编辑详情**********/
function editsmart(data, id) {
    myApp.showPreloader('发布中.....')
    var px = 0;
    var day = 0;
    var planid = "";
    var temp = null;
    var StrJson = new Array();
    var jsonParm = new Array();

    var templist = new Object();
    templist.CurTime = ISS.utils.dateToStr("yyyy-MM-dd", new Date())
    jsonParm.push(templist)
    templist = new Object();
    templist.PlanMainID = id
    jsonParm.push(templist)
    templist = new Object();
    var arr = new Array();
    $$('#plan-editdetail li').each(function (i, v) {
        if ($$(this).find('.day-tit').length == 1) {
            px = 1; day++; planid = $$(this).find('div').eq(0).attr('planDayID')
        } else {
            var temp = findobj(data, $$(this).attr('dayname'), $$(this).attr('projectid'));
            if (temp != null) {
                arr.push(setnewobj(px, day, planid, temp));
                px++;
            }
        }
    })
    templist.StrJson = JSON.stringify(arr);
    jsonParm.push(templist);
    var conditionParams = {
        serviceName: ISS_Constants.PortalServiceName.AddSmarttragel,
        Type: 3,
        action: 2,
        content: JSON.stringify({
            Calltype: "T_5",
            jsonParm: jsonParm
        }),
    };
    $$.ajax({
        url: ISS_Constants.Url.const_portal_url,
        data: conditionParams,
        dataType: 'jsonp',
        jsonp: 'callback',
        type: "post",
        success: function (data, status) {
            if (data == "True") {
                myApp.hidePreloader();
                myApp.alert('修改成功', function () {
                    location.reload();
                })
            } else {
                myApp.hidePreloader();
                myApp.alert('修改成功', function () {
                    location.reload();
                })
            }
        },
        error: function (xhr, status) {
            myApp.hidePreloader();
            myApp.alert('修改成功', function () {
                location.reload();
            })
        }
    });
}
function findobj(data, dayName, projectid) {
    var obj = null;
    for (var i = 0; i < data.length; i++) {
        if (data[i].dayName == dayName && data[i].projectId == projectid) {
            obj = data[i];
            return obj;
        }
    }
}
function setnewobj(px, day, pd, temp) {
    var obj = new Object();
    obj.day = day,
        obj.protype = temp.projectType,
        obj.procode = temp.projectId,
        obj.proname = temp.projectName,
        obj.proshortname = temp.projectShortName,
        obj.price = temp.price,
        obj.px = px,
        obj.Remark = temp.remark,
        obj.times = temp.time == "" ? "2" : temp.time,
        obj.district = "",
        obj.planproid = "",
        obj.plandayid = "",
        obj.latitude = temp.latitude,
        obj.longitude = temp.longitude,
        obj.phone = "",
        obj.address = "",
        obj.imgurl = ""
    return obj;
}
/*************************/



